package com.zcf.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zcf.common.yunos.aliyun.MessageType;
import com.zcf.common.yunos.aliyun.SendMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zcf.common.utils.DateUtils;
import com.zcf.mapper.LogMapper;
import com.zcf.mapper.OrderMapper;
import com.zcf.mapper.OrderinfoMapper;
import com.zcf.pojo.Dining;
import com.zcf.pojo.Log;
import com.zcf.pojo.MyCoupon;
import com.zcf.pojo.Orderinfo;
import com.zcf.pojo.Orders;
import com.zcf.pojo.User;
import com.zcf.service.UserService;
import com.zcf.utils.AppPush;
import com.zcf.utils.Hutool;
import com.zcf.utils.zhifubao.ALiPayConfig;

@Controller
public class ALiPayController {
//	@Autowired
//	private UserService userService;
	@Autowired
	OrderinfoMapper orderMapper;
	@Autowired
	LogMapper logMapper;
	private static final Logger logger = LoggerFactory.getLogger(ALiPayController.class);

	// TODO 向支付宝发送请求前先获取订单编号
	/**
	 * @param request
	 * @param money   钱
	 * @param jifen   积分
	 * @param userid  用户Id
	 * @return
	 */
	@RequestMapping("carts/payAlis")
	@ResponseBody
	public String doGetCode(HttpServletRequest request, Orderinfo ordetResult) {
		String order = null;// 最后的返回值
		try {
			logger.info("-----------》创建支付宝订单: ");
			// 实例化客户端
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
					ALiPayConfig.appid, ALiPayConfig.private_key, "json", ALiPayConfig.input_charset,
					ALiPayConfig.ali_public_key, ALiPayConfig.pay_sign_type);
			// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
			AlipayTradeAppPayRequest request1 = new AlipayTradeAppPayRequest();
			// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
			model.setBody("欢迎使用小鸡外卖");
			Double money = ordetResult.getTotalMoney();
			System.out.println(money);
			model.setSubject("欢迎购买小鸡外卖商品花费:" + money + "元");
			model.setOutTradeNo(ordetResult.getOrderNumber());// 訂單號
			model.setTimeoutExpress("30m");// 時間
			model.setTotalAmount(money + "");// 金額
			model.setSellerId(ALiPayConfig.partner);
			model.setProductCode("QUICK_MSECURITY_PAY");
			request1.setBizModel(model);
			request1.setNotifyUrl(ALiPayConfig.notify_url);
			try {
				// 这里和普通的接口调用不同，使用的是sdkExecute
				AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request1);
				System.out.println(response.getBody());
				order = response.getBody();
				logger.info("-----------》创建支付宝订单成功: " + order);
			} catch (AlipayApiException e) {
				e.getMessage();
				order = "error";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			order = "error";
		}
		return order;
	}

	// 购买商品：支付后异步请求地址
	@RequestMapping("notify_url")
	@ResponseBody
	public void doOrderSecPayNotify(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>进入回调方法");
		try {
			// 获取支付宝POST过来反馈信息
			Map<String, String> params = new HashMap<String, String>();
			@SuppressWarnings("rawtypes")
			Map requestParams = request.getParameterMap();
			for (@SuppressWarnings("rawtypes")
			Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
					valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
					System.out.println(valueStr);
				}
				// 乱码解决，这段代码在出现乱码时使用。
				params.put(name, valueStr.trim());
			}
			try {
				boolean flag = AlipaySignature.rsaCheckV1(params, ALiPayConfig.ali_public_key,
						ALiPayConfig.input_charset, "RSA2");
				// 商户订单号
				String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
				// 支付宝交易号
				String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
				// 交易状态
				String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
				// 支付金额
				String totalFee = new String(request.getParameter("buyer_pay_amount").getBytes("ISO-8859-1"), "UTF-8");
				// 买家账号
				String buyerEmail = new String(request.getParameter("buyer_logon_id").getBytes("ISO-8859-1"), "UTF-8");
				System.out.println(">>>>>>>>>>>>>>>商户订单号:" + out_trade_no);
				System.out.println(">>>>>>>>>>>>>>>>>支付宝交易号" + trade_no);
				System.out.println(">>>>>>>>>>>>>>>>>>>>交易状态" + trade_status);
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>>支付金额" + totalFee);
				System.out.println(">>>>>>>>>>>>>>>>>>>>买家账号" + buyerEmail);
				if (flag) {// 验证
					if ("TRADE_FINISHED".equals(trade_status) || trade_status.equals("TRADE_SUCCESS")) {
						System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>支付成功后的逻辑");
						/** 支付成功后的逻辑 */
						String oid = out_trade_no;// 获取订单的Id
						Orderinfo orders1 = new Orderinfo();
						EntityWrapper<Orderinfo> entityWrapper = new EntityWrapper<>();
						entityWrapper.eq("order_number", oid);
						orders1 = orders1.selectOne(entityWrapper);
						if (orders1 != null) {
							if (orders1.getStatus() == 0) {

								System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>订单存在");
 								Dining dining = new Dining();
								dining = dining.selectById(orders1.getDinId());

								User users = new User();
								users = users.selectById(dining.getUserId());
								System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>cid");
								if (users != null) {
									if(users.getPhone()!=dining.getPhone()){
										SendMessage.send(MessageType.GETORDER, users.getPhone(),"1");
										SendMessage.send(MessageType.GETORDER, dining.getPhone(),"1");
									}else{
										SendMessage.send(MessageType.GETORDER, users.getPhone(),"1");
									}

									AppPush.pushinfo(users.getCid());
									System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>cid进入");
									System.out.println(users.getCid() + "==============");
								}


								orders1.setCompletionTime(Hutool.parseDateToString());// 鍥炶皟鎴愬姛鏃� 鎵ц
								orders1.setPayment("2");// 支付方式
								if(dining.getLargeId().equals("7")){
									orders1.setStatus(5);// 宸蹭粯娆� 鎴栬�� 寰呮敹璐�
								}else {
									orders1.setStatus(1);// 宸蹭粯娆� 鎴栬�� 寰呮敹璐�

								}
								orders1.setDinStatus(0);
								orders1.updateById();

//						if (orders1.getMyId() != null) {
//							MyCoupon myCoupon = new MyCoupon();
//							myCoupon.setId(orders1.getMyId());
//							myCoupon.deleteById();
//						}

								User user = new User();
								EntityWrapper<User> ew = new EntityWrapper<>();
								ew.eq("id", orders1.getUserId());
								user = user.selectOne(ew);
								// 娣诲姞鏃ュ織
								Log log = new Log();
								log.setAddtime(DateUtils.formatTimeNow());
								log.setLogDesc("支付宝支付");
								log.setLogType(2);
								double sum = (orders1.getTotalMoney() - Double.parseDouble(orders1.getCouponMoney()));
								log.setLogName(user.getName() + "消费了" + sum + "元");
								log.setLogId(Hutool.getId());
								log.setUserId(user.getId());
								log.setOrderId(out_trade_no);
								log.setMoneys(sum + "");
								logMapper.insert(log);
								System.out.println(">>>>>>>>>>>>>>>>>>>>>验证确认支付成功！！！！！！！！！！！");
								response.getWriter().print("success");
							}
							response.getWriter().print("success");
						}
						response.getWriter().print("success");
					}
				} else {// 验证失败
					response.getWriter().print("fail");
				}
			} catch (AlipayApiException e1) {
				response.getWriter().print("fail");
			}
		} catch (UnsupportedEncodingException e) {
			response.getWriter().print("fail");
		}
	}

}